/**
 * 金字塔专题图
 * 说明：展示人口金字塔等
 */
/*
 data: [{
   id: 'pyramid',
   name: '金字塔图',
   regioncode: "aaa",
   regionname: "aaa",
   lon: "0.92866163503169",
   lat: "30.830660058696104",
   width: '160px',
   height: '160px',
   max: 100,
   showThumbnails: true,
   labelData: ['65岁以上', '55-64岁', '45-54岁', '35-44岁', '25-34岁', '15-24岁', '5-14岁', '0-4岁'],
   barWidth: 5, // 每个柱状宽度,可选
   gridWidth: 48, // 0-50，可选，取百分比，
   showYAxis: false, // 是否显示y轴
   data: [{
       value: [50, 28, 80, 65, 68, 60, 35, 52],
       name: '女性年龄分布'
     },
     {
       value: [50, 28, 80, 65, 68, 60, 35, 52],
       name: '男性年龄分布'
     }
   ]
 }]
*/

import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sfgis.layer.base';
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
import styleModify from './echarts.stylemodify'; // 为设置图层的透明度，可见性，zIndex等引入
export default {
  activeMap: {}, // 当前活动地图
  radarLayer: '',
  radarLayerInfo: {}, // 图层其他相关信息
  /**
   * 创建地图饼图专题图
   */
  createLayer(map, data) {
    if (!map) {
      return;
    }
    if (!data || !data.data.length) {
      return;
    }
    this.activeMap = map;
    const pyramidMarkers = this.createMarker(data.data,map); // 创建好所有marker
    // const pyramidMarkers = this.createMarker(data.data); // 创建好所有marker
    // const pyramidLayer = L.layerGroup(pyramidMarkers)
    //   .addTo(map);
    const pyramidLayer = pyramidMarkers;
    styleModify.onZoom(this.activeMap, pyramidMarkers); // 为markers绘图添加缩放监听改变z-Index，由于markers的ZIndex会睡着纬度变化而变化，所以有此语句;
    // 此处必须先把容器加到地图上才能加载图表
    this.pyramidLayer = pyramidLayer;
    // 将容器加载到地图容器
    this.createCharts(pyramidMarkers, data.data);
    // 自定义颜色开始
    const layerId = "pyramid_chart_" + data.id + "_" + +new Date();
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    styleModify.setLayerOrder(styleModify.curZindex, pyramidLayer, layerId);
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    styleModify.layerOrder[layerId] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    pyramidLayer.setCustomColor = this.setCustomColor;
    pyramidLayer.setOpacity = styleModify.setOpaticty; // 设置图层透明度
    pyramidLayer.setVisible = styleModify.setVisible; // 设置图层可见性
    pyramidLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;
    pyramidLayer.calSeries = this.calSeries;
    pyramidLayer.autoCalgraph = this.autoCalgraph;
    pyramidLayer.charts = [...this.charts];
    pyramidLayer.layerId = layerId;
    // 自定义颜色结束
    const pyramidLayerInfo = {
      name: data.name,
      layerId,
      type: "pyramid",
      layer: pyramidLayer,
      show: data.showThumbnails !== false,
      html: this.calgraph(layerId)
    };
    this.pyramidLayerInfo = pyramidLayerInfo;
    sgisLayerBase.setOverLayers(pyramidLayerInfo);
    return pyramidLayerInfo;
  },
  /**
   * 创建echarts容器
   */
  createMarker(datas,map) {
    const resultMarkers = [];
    for (let i = 0; i < datas.length; i++) {
      const time = +new Date();
      // 初始化最小宽高开始
      const data = datas[i];
      let width = colorPicker.size;
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      const iconWidth = width + 35;
      const iconHeight = height + 35;

      var el = document.createElement('div');
      el.className = `pyramid_chart_${i}${time} chart_background`;
      el.id = "pyramid_chart_" + i + time;
      el.style.width =  iconWidth + 'px';
      el.style.height =  iconHeight + 'px';
      const chartMarker = new mapboxgl.Marker(el)
        .setLngLat([data.lon, data.lat])
        .addTo(map);
      // 初始化最小宽高结束
      // const chartMarker = L.marker([datas[i].lat, datas[i].lon], {
      //   id: "pyramid_chart_" + i + time, // 生成id
      //   pane: styleModify.pane, // 为设置自定义的图层顺序特别设定
      //   icon: L.divIcon({
      //     className: "",
      //     iconSize: [width, height],
      //     html: `
      //     <div id = "pyramid_chart_${i}${time}"
      //     style = "width:${width}px;height:${height}px;position:relative;background-color:transparent;z-index='99998';" >
      //     </div>
      //     `
      //   })
      // });
      resultMarkers.push(chartMarker);
    }
    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} pyramidMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(pyramidMarkers, datas) {
    const charts = [];
    const xAxis = {
      type: 'value',
      axisTick: {
        show: false,
        inside: false
      },
      axisLabel: {
        show: false
      },
      axisLine: { // Y轴轴线样式
        show: false,
        lineStyle: {
          color: colorPicker.pyramid.lineColor
        }
      },
      splitLine: {
        show: false
      }
    };
    for (let i = 0; i < datas.length; i++) {
      const chart = echarts.init(document.getElementById(pyramidMarkers[i]._element.id));
      let gridWidth = '48%';
      let left = '52%';
      if (datas[i].hasOwnProperty('gridWidth')) {
        gridWidth = datas[i].gridWidth + '%';
        left = 100 - datas[i].gridWidth + '%';
      }
      const chartOption = {
        backgroundColor: 'transparent',
        // legend: this.calLgend(datas[i]),
        // tooltip（提示框组件）
        tooltip: {
          // trigger(触发类型)，可选'item','axis','none'
          trigger: 'axis',
          axisPointer: {
            // 指示器类型,可选'line','shadow','cross'
            type: 'shadow'
          }
        },
        xAxis: [{
          ...xAxis,
          gridIndex: 0,
          axisTick: {
            show: false,
            inside: false
          },
          min: datas[i].max * -1,
          max: 0
        }, {
          ...xAxis,
          gridIndex: 1,
          axisTick: {
            show: false
          },
          min: 0,
          max: datas[i].max
        }],
        yAxis: this.calYAxis(datas[i]),
        grid: [{
          top: 30,
          width: gridWidth,
          left: 0,
          gridIndex: 0
        }, {
          top: 30,
          left,
          width: gridWidth,
          gridIndex: 1
        }],
        color: colorPicker.color,
        series: this.calSeries(datas[i])
      };
      chart.setOption(chartOption);
      charts.push({
        id: pyramidMarkers[i]._element.id,
        echart: chart
      });
    }
    this.charts = charts;
    /* *图标创建结束 */
  },
  /**
   * 自定义金字塔图标颜色
   * par:{
   * pyramidStyle: [this.color1, "tomato"], //金字塔2个柱状颜色
     barWidth: 5, // 每个柱状宽度,可选
   * }
   */
  setCustomColor(layers, pars) {
    let par = {};
    par = {
      ...pars,
      pyramidStyle: pars.colors
    };
    for (const key in layers.charts) {
      const item = layers.charts[key];
      const option = item.echart.getOption();
      // 设置金字塔柱状颜色开始
      if (par.hasOwnProperty('pyramidStyle')) {
        option.color = par.pyramidStyle;
        const data = option.series;
        option.series = layers.calSeries({
          data
        }, par);
      }
      // 设置金字塔柱状颜色结束
      item.echart.setOption(option);
    }
    layers.autoCalgraph(layers.layerId, pars.colors);
  }, // 自定义金字塔图标颜色
  /* *legend格式化 */
  calLgend(data) {
    const legend = {
      orient: 'horizontal', // 'vertical'
      x: 'center', // 'center' | 'left' | {number},
      y: 'top', // 'center' | 'bottom' | {number}
      data: ""
    };
    const arr = [];
    for (const item of data.data) {
      arr.push({
        name: item.name,
        textStyle: {
          fontWeight: 'normal'
          // padding: [10, 100, 15, 0]
          // color:'#cccccc'
        },
        icon: ""
      });
    }
    legend.data = arr;
    return legend;
  },
  /* *y轴样式格式化 */
  calYAxis(data) {
    const axis = {
      type: 'category',
      inverse: true,
      data: data.labelData,
      axisTick: {
        show: false
      },
      axisLine: { // Y轴轴线样式
        show: false,
        lineStyle: {
          color: colorPicker.pyramid.lineColor
        }
      }
    };
    const yAxis = [{
      ...axis,
      gridIndex: 0,
      axisLabel: {
        show: false,
        fontSize: '12px'
      }
    }, {
      ...axis,
      gridIndex: 1,
      axisLabel: {
        show: data.showYAxis,
        fontSize: '12px'
      }
    }];
    return yAxis;
  },
  /* *数据格式化计算 */
  calSeries(data, par) {
    const series = [];
    if (par) {
      data.data[0].value = data.data[0].data;
      data.data[1].value = data.data[1].data;
    } else {
      for (const index in data.data[0].value) {
        data.data[0].value[index] = data.data[0].value[index] * -1;
      }
    }
    let color = '';
    let position = '';
    let barWidth = '5';
    if (data.hasOwnProperty('barWidth')) {
      barWidth = data.barWidth;
      // 自定义颜色开始
      if (par && par.hasOwnProperty('barWidth')) {
        barWidth = par.barWidth;
      }
      // 自定义颜色介绍
    }
    this.graph = []; // 为定义图例样式定制变量
    for (const index in data.data) {
      switch (index) {
        case '0':
          if (par && par.hasOwnProperty('pyramidStyle')) {
            color = par.pyramidStyle[0];
          } else {
            color = data.data[index].color ? data.data[index].color :
              colorPicker.pyramid.color[0];
          }
          position = 'left';
          break;
        case '1':
          if (par && par.hasOwnProperty('pyramidStyle')) {
            color = par.pyramidStyle[1];
          } else {
            color = data.data[index].color ? data.data[index].color :
              colorPicker.pyramid.color[1];
          }
          position = 'right';
          break;
        default:
          break;
      }
      this.graph.push({
        name: data.data[index].name,
        color
      });
      const options = {
        name: data.data[index].name,
        type: 'bar',
        barWidth,
        itemStyle: {
          normal: {
            show: true,
            color,
            barBorderRadius: 50,
            borderWidth: 0,
            borderColor: '#333',
            label: {
              show: true,
              position,
              formatter(v) {
                return '';
                // if (index === 0) {
                //   return v.value * -1;
                // } else {
                //   return v.value;
                // }
              }
            }
          }
        },
        data: data.data[index].value
      };
      if (index === '0') {
        options.gridIndex = 0;
      } else {
        options.xAxisIndex = 1;
        options.yAxisIndex = 1;
      }
      series.push(options);
    }
    return series;
  },
  /**
   * @param {string} layerId 图层id
   */
  /* *设置图例样式 开始 */
  calgraph(layerId) {
    let html = `<div style="padding:6px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div class='chart_item'>
        <div style='display:inline-block;width:20px;height:3px;background:${this.graph[key].color};margin:0;padding:0;border-radius:50px;'>
        <p>${this.graph[key].name}</p>
        </div>
      </div>`;
    }
    html += '</div>';
    return html;
  },
  /**
   * @param {string} layerId 图层id
   */
  autoCalgraph(layerId, colors) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div class='chart_item'>
        <div style='display:inline-block;width:20px;height:3px;background:${colors[key]};margin:0;padding:0;border-radius:80px;'>
        <p>${this.graph[key].name}</p>
        </div>
      </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    // sgisLayerBase.layerControlChange();
  },
  /* *设置图例样式 结束 */
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
